<?php

namespace App\Http\Controllers;

use App\Utils\Loader;
use hyang\SuPigeons;
use hyang\Util;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

Loader::lib('hyang');

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    // hyang/pigeons
    protected $pigeons;
    private $jsVarStack = array(); // 前端处理数据
    /**
     * 页面参数配置
     * @param $config array
     * @return array
     */
    protected function pageInit($config){
        $data = ['js'=>'','css'=>''];
        if(isset($config['title'])) $data['title'] = $config['title']; // aurora_title
        $baseurl = request()->getBaseUrl();
        $randStr = config('app.debug')? '?v='.Util::randStr(10):'';
        $baseSrc = config('aurora.baseurl');
        if(isset($config['js'])){
            $jses = is_array($config['js'])? $config['js']:[$config['js']];
            foreach ($jses as $js){
                $js = $baseSrc . ((strpos($js, '/') === 0)? '':'/js/') . $js;
                $data['js'] .= '<script src="'.$baseurl.$js.'.js'.$randStr.'"></script>';
            }
        } // aurora_js
        if(isset($config['css'])){
            $csses = is_array($config['css'])? $config['css']:[$config['css']];
            foreach ($csses as $css){
                $css = $baseSrc . ((strpos($css, '/') === 0)? '':'/css/') . $css;
                $data['css'] .= '<link rel="stylesheet" href="'.$baseurl.$css.'.css'.$randStr.'" />';;
            }
        }; // aurora_css
        return empty($data)? $data:['a__tpl'=>$data];
    }
    /**
     * 获取根地址
     * @return string
     */
    protected function getBaseUrl(){
        $port = request()->getPort();
        return $_SERVER['REQUEST_SCHEME'].'://'.request()->getHost().($port == '80' && $port == '443'? '':':'.$port);
    }
    /**
     * 获取主页基础地址
     * @return string
     */
    protected function getHomeUrl($url=null){
        return $this->getBaseUrl().'/'.config('aurora.home_base_url').($url? $url:'');
    }
    /**
     * 获取用户信息数据
     * @param null $key
     * @param $parseMk true
     * @return array|mixed|string
     */
    protected function getUserInfo($key=null,$parseMk=false){
        if($parseMk){
            if(empty($key)) return "";
            $skey = $this->aurora('php_session.user_key');
            $userInfo = Util::BaseJson($key);
            if ($userInfo && is_array($userInfo)) {
                session([$skey=>$userInfo]);
            }
            return $userInfo;
        }
        $skey = $this->aurora('php_session.user_key');
        $data = $skey? session($skey):'';
        //debug($data, $skey);
        return is_array($data) && isset($data[$key])? $data[$key]:'';
    }
    /**
     * 项目配置表获取
     * @param $key
     * @param string $delimiter
     * @return mixed
     */
    protected function aurora($key,$delimiter='.'){
        $redisCs = (in_array($key,config('aurora.redis_keys_cache')))? true:false;
        if($redisCs){
            $value = $this->redis($key);
            if($value) return $value;
        }
        $idx = strpos($key,$delimiter);
        $groupid = $idx > 0? substr($key,0,$idx):'';
        $setting_key = $groupid? str_replace($groupid.'.','',$key):$key;
        $prj = config('aurora.PROJECT_NAME');
        $where = ['prj1001c.setting_key'=>$setting_key,'prj1000c.code'=>$prj];
        if($groupid) $where['prj1001c.groupid'] = $groupid;
        $data = DB::table('prj1001c')
            ->select(DB::raw('ifnull(prj1001c.short_text,prj1001c.long_text) as value,prj1001c.json_text as json'))
            ->join('prj1000c','prj1001c.pid','=','prj1000c.listid')
            ->where($where)
            ->first()
        ;
        $data = (array)$data;
        $value = $data['value']? $data['value']:json_decode($data['json']);
        if($redisCs) $this->redis($key,$value);
        return $value;
    }
    /**
     * 项目内redis缓存处理
     * @param $key
     * @param null $value
     * @param $default string/callback
     * @return mixed
     */
    protected function redis($key,$value=null,$default=null){
        try {
            $key = config('aurora.Redis_pref') . $key;
            if (empty($value)) {
                $value = Redis::get($key);
                if (empty($value) && $default) {
                    return ($default instanceof \Closure) ? call_user_func($default) : $default;
                }
                return $value;
            } else Redis::set($key, $value);
        }catch (\Exception $e){
            debug($e->getMessage());
        }
        return false;
    }
    /**
     * 前端js值传递
     * @param $key
     * @param null $value
     * @return mixed|string
     */
    protected function jsVar($key,$value=null){
        if(null !== $value) $this->jsVarStack[$key] = $value;
        else if(is_array($key)){
            $this->jsVarStack = array_merge($this->jsVarStack,$key);
        }else return isset($this->jsVarStack[$key])? $this->jsVarStack[$key]:'';
    }
    /**
     * js 脚本生成器
     * @return string
     */
    protected function crtJsVarScpt(&$data=null){
        $var = '<script>var _Aurora = '.json_encode($this->jsVarStack).';</script>';
        if(empty($data)) return $var;
        $data['a__script'] = $var;
    }

    /**
     * 获取登录用户信息
     * @return array
     */
    protected function getUserJsVar(){
        $data = [];
        $user = $this->getUserInfo('user');
        if($user) $data['user'] = $user;
        if($data) $this->jsVar($data);
    }

    /**
     * 登录验证，没有登录时限制权限
     */
    protected function checkLogin($auth=''){
        if('' == $auth){
            $user = $this->getUserInfo('user');
            if(empty($user)){
                $header = redirect()->action('Index\\Error@Action', ['msg' => '您还没有登录系统，或者登录状态失效了']);
                die($header);
            }
        }
    }
    /**
     * @return SuPigeons
     */
    protected function getPigeons(){
        if(!$this->pigeons){
            // SuPigeons::getInstance(config('pigeons.'.env('APP_ENV')))
            $this->pigeons = SuPigeons::getInstance(config('pigeons.'.env('APP_ENV')));
        }
        return $this->pigeons;
    }
}
